package com.czy.workflow.demo;

import com.czy.workflow.core.context.FlowContext;
import com.czy.workflow.core.exception.FlowException;
import com.czy.workflow.core.model.FlowMain;
import com.czy.workflow.core.model.FlowNode;
import com.czy.workflow.core.model.vo.FlowNodeVO;
import com.czy.workflow.core.model.vo.FlowOptionVO;
import com.czy.workflow.core.service.FlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/workflow")
public class WorkController {


    @Autowired
    FlowContext flowContext;

    @PostMapping("/saveFlow")
    public Boolean saveFlow(@RequestBody FlowMain flowMain){
        return flowContext.getFlowService().saveFlowMain(flowMain);
    }

    @GetMapping("/getFlow")
    public FlowMain getFlow(String flowId){
        return flowContext.getFlowService().getFlowMainById(flowId);
    }


    /**
     * 流程操作提交接口
     * @param docId 任务id
     * @param nodeId 节点id
     * @param option 分支可选项
     * @return
     */
    @PostMapping("/submit/{docId}/{nodeId}")
    public Boolean submit(@PathVariable("docId")String docId, @PathVariable("nodeId")String nodeId, String option){
        try {
            return flowContext.getTaskExecutor().execute(docId, nodeId, option);
        } catch (FlowException e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 文档操作可选项
     * @description 一个用户可能同时操作多个节点，每个节点又有不同选项
     * @param docId
     * @return {taskId, flowNodes:[{nodeId, options:[]}]}
     */
    @GetMapping("/taskNodeBranches/{docId}")
    public FlowOptionVO getCurrentNodeBranches(@PathVariable("docId")String docId){

        FlowOptionVO flowOptionVO = new FlowOptionVO();
        flowOptionVO.setDocId(docId);

        FlowService flowService = flowContext.getFlowService();

        List<FlowNode> flowNodes = flowService.getCurrentNodes(docId);
        List<FlowNodeVO>  flowNodeVOS = new ArrayList<>();

        for(FlowNode flowNode : flowNodes){
            flowNodeVOS.add(FlowNodeVO.build(flowNode, flowService.getNodeBranches(flowNode.getFlowId(), flowNode.getId())));
        }

        return flowOptionVO;
    }


    //TODO:日志接口



}
